package com.huatai.exchange.send;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.CloseUtils;
import com.faneui.integration.smb.SmbFileUtils;
import com.huatai.exchange.integration.base.service.FileOperateService;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.util.Map;

@Service("fileSmbSendService")
public class FileSmbSendServiceImpl extends AbstractFileSendServiceImpl implements FileSendService {

    @Autowired
    private FileOperateService fileOperateService;

    @Override
    public void sendMessage(String destAddress, Map<String, Object> resvMap) throws BusinessException {
        boolean b = resvMap.get("fileNames") == null || StringUtils.isBlank((String) resvMap.get("fileNames"));
        String fileNames = b ? null : (String) resvMap.get("fileNames");
        String filePaths = b ? null : (String) resvMap.get("filePaths");
        // 不通过  通讯系统

        NtlmPasswordAuthentication auth = null;
        //destAddress = formatStr(destAddress,resvMap) ;
        if (!destAddress.contains("smb")) {
            destAddress = SmbFileUtils.H_url + destAddress;
            auth = SmbFileUtils.createAuthHdisk();
        } else {
            //TODO 暂不实现
        }
        // 文件夹 是否创建
        try {
            SmbFile dir = new SmbFile(destAddress, auth);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String[] names = fileNames.split(",");
            String[] paths = filePaths.split(",");

            for (int i = 0; i < names.length; i++) {
                download(destAddress + names[i], auth, paths[i]);
            }
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BusinessException(ex.getMessage());
        }
    }

    private void download(String smbFileUrl, NtlmPasswordAuthentication auth, String filePath) throws BusinessException {
        OutputStream os = null;
        try {
            os = new SmbFileOutputStream(new SmbFile(smbFileUrl, auth));
            fileOperateService.downloadFile(os, filePath);
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BusinessException(ex.getMessage());
        } finally {
            CloseUtils.safeClose(os);
        }
    } 
}
